package mysql

import (
	"reflect"
	"strings"
	"time"
)

func getTableName(t reflect.Type, v reflect.Value) string {
	tablename := t.Name()
	m := v.MethodByName(TableName)
	if m != empthv {
		tablename = m.Call([]reflect.Value{})[0].String()
	}
	return tablename
}

func getPk(t reflect.Type, v reflect.Value) (pkkey string, pk int64) {
	for k := 0; k < t.NumField(); k++ {
		vs := t.Field(k).Tag.Get(Tag)
		if vs != "" {
			if strings.Index(vs, pkindex) > -1 {
				vs = strings.Split(vs, separate)[0]
				pkkey = vs
				pk = v.Field(k).Int()
				return
			}
		}
	}
	return
}

func insert(t reflect.Type, v reflect.Value, tablename string) (query string, param []interface{}) {
	var field []string
	var value []string

	for k := 0; k < t.NumField(); k++ {
		tagv := t.Field(k).Tag.Get(Tag)
		tagvs := strings.Split(tagv, separate)
		vs := tagvs[0]
		if strings.Index(tagv, pkindex) > -1 {
			//if vs != "id" {
			//field = append(field, vs)
			//value = append(value, valuereplace)
			//pk = strings.ToUpper(uuid.NewV4().String())
			//param = append(param, pk)
			//}
			continue
		}
		if vs != "" {
			field = append(field, vs)
			value = append(value, valuereplace)
			switch v.Field(k).Interface().(type) {
			case time.Time:
				param = append(param, v.Field(k).Interface().(time.Time).Format(timeDefaultFormat))
			default:
				param = append(param, v.Field(k).Interface())
			}
		}
	}
	query = "INSERT INTO " + tablename + " (" + strings.Join(field, ",") + ") VALUES (" + strings.Join(value, ",") + ")"
	return
}

func update(t reflect.Type, v reflect.Value, tableName string) (pk int64, query string, param []interface{}) {
	var field []string
	for k := 0; k < t.NumField(); k++ {
		vs := t.Field(k).Tag.Get(Tag)
		if vs != "" {
			if strings.Index(vs, pkindex) > -1 {
				pk = v.Field(k).Int()
				continue
			}
			field = append(field, vs+"=?")
			switch v.Field(k).Interface().(type) {
			case time.Time:
				param = append(param, v.Field(k).Interface().(time.Time).Format(timeDefaultFormat))
			default:
				param = append(param, v.Field(k).Interface())
			}
		}
	}
	query = "UPDATE " + tableName + " SET " + strings.Join(field, ",") + " WHERE id=?"
	param = append(param, pk)
	return
}
